import React, { FC, useEffect, useState, useRef, useMemo } from "react";
import QusetionCard from '../../components/QuestionCard'
import ListSearch from "../../components/ListSearch";
import styles from './common.module.scss'
import { JSX } from "react/jsx-runtime";
import { Empty, Spin } from 'antd'
import { useSearchParams } from 'react-router-dom'
import { useDebounceFn, useRequest } from 'ahooks'
import { getQuestionListService } from '../../services/question'
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../constant/index'
const List: FC = () => {
    const [started,setStarted]=useState(false)  
    const [page, setPage] = useState(1)  //List内部数据，不在url参数体现
    const [list, setList] = useState([]) //累计的全部列表数据
    const [total, setTotal] = useState(0)

    const haveMoreData = total > list.length
    const containerRef = useRef<HTMLDivElement>(null)

    const [SearchParams] = useSearchParams()
    const keyword=SearchParams.get(LIST_SEARCH_PARAM_KEY) || ""
    useEffect(()=>{      
        setStarted(false)
        setList([])
        setTotal(0)
        setPage(1)
    },[keyword])
    //真正加载数据
    const { run: load, loading } = useRequest(async () => {
        const data = await getQuestionListService({
            page,
            pageSize: LIST_PAGE_SIZE,
            keyword,
        })
        return data
    }, {
        manual: true,
        onSuccess(result) {
            const { list: l = [], total = 0 } = result
            setList(list.concat(l))//累计列表
            setTotal(total)
            setPage(page + 1)
        }

    })

    //触发加载(防抖)
    const { run: tryLoadMore } = useDebounceFn(() => {
        const elem = containerRef.current
        if (elem == null) return
        const domRect = elem.getBoundingClientRect()
        if (domRect == null) return
        const { bottom } = domRect
        if (bottom <= document.body.clientHeight) {
            load()
            setStarted(true)
        }
    }, {
        wait: 1000
    })
    //当页面加载和url参数变化，触发加载
    useEffect(() => {
        tryLoadMore()
    }, [SearchParams])
    useEffect(() => {
        if(haveMoreData){
        window.addEventListener('scroll', tryLoadMore) //防抖
        }
        return () => {
            window.removeEventListener('scroll', tryLoadMore) //解绑事件
        }
    }, [SearchParams,haveMoreData])
    const LoadMoreContentElem=useMemo(()=>{

        if(!started || loading) return <Spin></Spin>
        if(total===0) return <Empty></Empty>
        if(!haveMoreData) return <span>沒有更多了！！！</span>
        return  <span><Spin></Spin></span>
    } ,[started,loading,haveMoreData])
    return <>

        <div className={styles.header}>
            <div className={styles.left}>
                <span>问卷列表</span>
            </div>
            <div className={styles.right}>
                <ListSearch />
            </div>
        </div>

        <div className={styles.content}>
            {list.length > 0 && list.map((q: JSX.IntrinsicAttributes & { _id: string; title: string; isStar: boolean; isPublished: boolean; answerCount: number; createdAt: string; }) => {
                const { _id } = q
                return <QusetionCard key={_id} {...q} />
            })}

        </div>
        <div className={styles.footer}>
            <div ref={containerRef}>
              {LoadMoreContentElem}
            </div>
        </div>
    </>
}

export default List

